import _typeof from 'babel-runtime/helpers/typeof';
/* eslint-disable no-shadow */
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import createBrowserHistory from 'history/createBrowserHistory';
import { ConnectedRouter } from 'react-router-redux';

import configStore from './configStore';
import { createReducer } from './reducers';
import Root from './root';

var browserHistory = createBrowserHistory(); // eslint-disable-line import/no-mutable-exports

export default function createApp() {
  var initReducers = {};
  var store = null;
  var currentView = null;
  var currentReducer = null;
  var currentMiddlewares = []; // Create a browser history by default

  function view(view) {
    currentView = view;

    return this;
  }

  function reducer() {
    var reducers = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

    // If passed with {"reducer1": reducer1, "reducer2": reducer2, ...}
    // Then combine the `system` reducer
    if ((typeof reducers === 'undefined' ? 'undefined' : _typeof(reducers)) === 'object') {
      currentReducer = createReducer(reducers);
      initReducers = reducers;
    } else {
      currentReducer = reducers;
    }

    return this;
  }

  function middleware(middlewares) {
    currentMiddlewares = middlewares;

    return this;
  }

  function render(container, callback) {
    ReactDOM.render(React.createElement(
      Provider,
      { store: store },
      React.createElement(Root, { view: currentView, store: store })
    ), container, callback);
  }

  function run(container, callback) {
    if (typeof container === 'string') {
      container = document.querySelector(container); // eslint-disable-line  no-param-reassign
    }

    if (!currentReducer) {
      this.reducer();
    }

    store = configStore(currentReducer, browserHistory, currentMiddlewares);
    store.asyncReducers = initReducers;

    render(container, callback);

    return this;
  }

  function createHistory(options) {
    browserHistory = createBrowserHistory(options);

    return this;
  }

  function getStore() {
    return store;
  }

  return {
    view: view,
    reducer: reducer,
    middleware: middleware,
    run: run,
    createHistory: createHistory,
    getStore: getStore
  };
}

export { browserHistory, ConnectedRouter };
import _asyncComponent from './components/asyncComponent';
export { _asyncComponent as asyncComponent };